<?php

namespace App\Support;


use App\Kuafu\Order\Enum\OrderCodeEnum;
use App\Kuafu\Order\Exceptions\OrderException;
use App\Kuafu\Order\Service\OrderStatisticsService;
use App\Kuafu\Shop\Service\ShopService;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use Kuafu\File\FileUtil;

/**
 * 订单导出
 */
class ExcelService
{
    public function salesGoodsExcel(int $shopId, string $startAt, string $endAt, string $orderBy, string $byType, int $source,  bool $streamExport = true, int $isReturnData = 0)
    {
        $shopInfo       = ShopService::getShopInfo($shopId);
        $startAt        = (int)strtotime($startAt);
        $endAt          = (int)strtotime($endAt);
        $orderBy        = $orderBy ?: 'num';
        $byType         = $byType ?: 'desc';
        $source         = (int)$source ?: 1;
        $dataArr        = (new OrderStatisticsService)->bProductSellStatistics($startAt, $endAt, $shopId, $orderBy,
            $byType, $source);
        $dataArr        = OrderStatisticsService::divideInteger($dataArr, 100);
        $fieldArr       = array('菜品名称', '菜品规格', '订单来源', '销售数量', '销量占比', '营业额', '营业额占比', '营业收入', '营业收入占比', '优惠', '优惠占比');
        $fileName       = $shopInfo['name'] . '菜品销售统计' . date('Y-m-d', $startAt) . '-' . date('Y-m-d', $endAt);
        $tName          = '菜品销售统计';
        $fieldArrColumn = array(
            'productName',
            'unit',
            'sourceType',
            'num',
            'saleProportion',
            'originalPrice',
            'originalPriceProportion',
            'payPrice',
            'payProportion',
            'discount',
            'discountProportion',
        );
        $theadArr       = [
            '店铺' => $shopInfo['name'],
            '时间' => date('Y-m-d H:i:s', $startAt) . '-' . date('Y-m-d H:i:s', $endAt)
        ];
        if ($isReturnData) {// 直接返回数据
            return [$dataArr['list'], $fieldArr, $shopInfo];
        }

        return (new ExcelService)->exportExcel($dataArr['list'], $fieldArr, $tName, $fileName, $fieldArrColumn, $theadArr, $streamExport);
    }

    /**
     * 数据导出
     * @param $dataArr array 原始数据 二维数组
     * @param $fieldArr array 表头名
     * @param string $name 表头内容描述
     * @param string $fileName 表头内容值
     * @param $fieldArrColumn array 数据库字段 与 $fieldArr 相对应
     * @param $theadArr array 表头对应内容
     * @throws OrderException
     */
    function exportExcel(
        array $dataArr,
        array $fieldArr,
        string $name,
        string $fileName,
        array $fieldArrColumn,
        array $theadArr,
        bool $streamExport = true
    ) {
        if (!is_array($fieldArr) || empty($fieldArr)) {
            throw new OrderException(OrderCodeEnum::ERR_SERVER_ERROR, '导出异常，请重试');
        }
        if (!empty($dataArr) && count($dataArr) > 10000) {
            throw new OrderException(OrderCodeEnum::ERR_SERVER_ERROR, '单次导出的数据量过大（≥10000条），请分批导出！');
        }
        $thead = ''; //表头
        $tbody = ''; //表数据
        $clos  = count($fieldArr); //列数（字段量）
        //生成表头
        $thead .= '<tr><td colspan="' . $clos . '"> 报表内容：' . $name . '</td></tr>';
        foreach ($theadArr as $key => $value) {
            $thead .= '<tr><td colspan="' . $clos . '">' . $key . "：" . $value . '</td></tr>';
        }
        $thead .= '<tr><td colspan="' . $clos . '"> 导出时间:' . date("Y-m-d H:i:s") . ' </td></tr>';
        foreach ($fieldArr as $k => $v) {
            $thead .= '<td style="color:#fff;background-color:green;">' . $v . '</td>';
        }
        $thead .= '</tr>';
        //生成表尾
        $ttail = '<tr></tr>';
        //生成需要导出的数据源
        $datas = array();
        foreach ($dataArr as $k => $v) {
            $fieldFormat = []; //这里需要复制原本的字段格式，以防标题和内容没对应上
            if (!empty($v) && is_array($v)) {
                foreach ($v as $k2 => $v2) {
                    //根据key值决定当前字段是否需要导出
                    if (in_array($k2, $fieldArrColumn)) {
                        $fieldFormat[$k2] = $v2;
                    }
                }
            }
            $datas[] = $fieldFormat;
        }
        //生成表体
        foreach ($datas as $k => $v) {
            $tbody .= '<tr>';
            foreach ($v as $k2 => $v2) {
                if (!is_numeric($v2)) {
                    $tbody .= '<td style="vnd.ms-excel.numberformat:@">' . $v2 . '</td>';
                } else {
                    $tbody .= '<td>' . $v2 . '</td>';
                }
            }
            $tbody .= '</tr>';
        }
        $content = $thead . $tbody . $ttail;

        if ($streamExport) {

            // 数据流导出
            header("content-type:application/octet-stream; charset=utf8");
            header("Content-Disposition:attachment;filename=" . urlencode($fileName) . ".xls");
            echo "<table align='center' border=1 bgcolor='F8F7ED'>";
            if (mb_detect_encoding($content) != 'UTF-8') {
                echo iconv('UTF-8', "GB2312", $content);
            } else {
                echo $content;
            }
            echo "</table>";
        } else {

            $fd = "<table align='center' border=1 bgcolor='F8F7ED'>";
            $fd .= $content;
            $fd .= "</table>";

            return $fd;
        }
    }
}
